package com.homer.gps.track;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;

import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.SubMenu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.homer.gps.track.helper.GMapV2Directions;
import com.homer.gps.track.helper.UsefullStaff;
import com.homer.gps.track.persist.DatabaseHelper;
import com.homer.gps.track.persist.PlaceModel;
import com.homer.gps.track.persist.Repository;
import com.homer.gps.track.persist.RouteModel;
import com.homer.gps.track.persist.StopModel;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.ForeignCollection;

public class MapActivity extends SherlockFragmentActivity  {
	private GoogleMap map;
	private Repository repository;
	private DatabaseHelper dbHelper = null;

	private PlaceModel selectedPlace = null;
	private RouteModel selectedRoute = null;
	private int selectedPlaceId = -1;
	private int selectedRouteId = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);
		this.map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
		this.repository = new Repository(getHelper());
		initActivity();
		selectedPlaceId = getIntent().getIntExtra("placeId", -1);
		if (selectedPlaceId > -1) {
			selectedPlace = repository.getPlaceForId(selectedPlaceId);
			showPlace();
		}
		selectedRouteId = getIntent().getIntExtra("routeId", -1);
		if (selectedRouteId > -1){
			selectedRoute = repository.getRouteForId(selectedRouteId);
			showRoute();
		}
	}

	private void initActivity(){
		if (selectedPlace != null) {
			getSupportActionBar().setTitle(selectedPlace.getName().toString());
			getSupportActionBar().setHomeButtonEnabled(true);
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
			getSupportActionBar().setIcon(UsefullStaff.getPlaceTypeImageResource(selectedPlace.getType()));
		}
	}

	private void showPlace(){
		List<Address> foundGeocode = null;

		/* find the addresses  by using getFromLocationName() method with the given address*/
		try {
			foundGeocode = new Geocoder(this).getFromLocationName(selectedPlace.getParsedAddress().toString(), 1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (foundGeocode != null) {
			LatLng positionLatLng = new LatLng(foundGeocode.get(0).getLatitude(), foundGeocode.get(0).getLongitude());
			Marker placeMarker = map.addMarker(new MarkerOptions().position(positionLatLng)
					.title(selectedPlace.getName().toString())
					.snippet(selectedPlace.getNote().toString())
					.icon(BitmapDescriptorFactory.fromResource(UsefullStaff.getPlaceTypeImageResource(selectedPlace.getType()))));
			map.moveCamera(CameraUpdateFactory.newLatLngZoom(positionLatLng, 15));
		}
	}
	
	private void showRoute(){
		ForeignCollection<StopModel> routeStops = selectedRoute.getStops();
		PolylineOptions line = new PolylineOptions();
		List<LatLng> points = new ArrayList<LatLng>();
		//List<StopModel> routeStops = (List<StopModel>) selectedRoute.getStops();
		for (StopModel stop : routeStops) {
			PlaceModel stopPlace = null;
			try {
				stopPlace = repository.lookupPlacesForStop(stop);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			if (stopPlace != null) {
				List<Address> foundGeocode = null;

				/* find the addresses  by using getFromLocationName() method with the given address*/
				try {
					foundGeocode = new Geocoder(this).getFromLocationName(stopPlace.getParsedAddress().toString(), 1);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if (foundGeocode != null) {
					LatLng positionLatLng = new LatLng(foundGeocode.get(0).getLatitude(), foundGeocode.get(0).getLongitude());
					Marker placeMarker = map.addMarker(new MarkerOptions().position(positionLatLng)
							.title(stopPlace.getName().toString())
							.snippet(stopPlace.getNote().toString())
							.icon(BitmapDescriptorFactory.fromResource(UsefullStaff.getPlaceTypeImageResource(stopPlace.getType()))));
					map.moveCamera(CameraUpdateFactory.newLatLngZoom(positionLatLng, 15));
			
					line.add(positionLatLng);
					points.add(positionLatLng);
				}
			}
			
		}
		if (line != null) {
			line.geodesic(true).color(Color.RED).width(5);
			map.addPolyline(line);
		}
		if (points != null) {
			getDirections(points);
		}
	}

	private DatabaseHelper getHelper() {
		if (dbHelper == null) {
			dbHelper = (DatabaseHelper)OpenHelperManager.getHelper(this, DatabaseHelper.class);
		}
		return dbHelper;
	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		SubMenu subMenu = menu.addSubMenu("Type");
		subMenu.add(0, 0, 0, R.string.map_normal_view);
		subMenu.add(0, 1, 0, R.string.map_satellite_view);
		subMenu.add(0, 2, 0, R.string.map_hybrid_view);
		subMenu.add(0, 3, 0, R.string.map_terrain_view);
		subMenu.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		subMenu.getItem().setIcon(R.drawable.map_eye);
		return true;
	}


	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
		if (map != null){
			switch (item.getItemId()) {
			case android.R.id.home:
				finish();
				break;
			case 0:
				map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
				break;
			case 1:
				map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
				break;
			case 2:
				map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
				break;
			case 3:
				map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
				break;
			default:
				map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
				break;
			}
		}
		return true;

	}
	
	private void getDirections(List<LatLng> points){
		Log.e("poins count", String.valueOf(points.size()));
		if (points.size()>1) {
			GMapV2Directions md = new GMapV2Directions();
			//if (md != null) {
				Document doc = md.getDocument(points.get(0), points.get(points.size()-1), GMapV2Directions.MODE_DRIVING);
				if (doc != null) {
					ArrayList<LatLng> directionPoint = md.getDirection(doc);
					PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.BLUE);

					for(int i = 0 ; i < directionPoint.size() ; i++) {          
					rectLine.add(directionPoint.get(i));
					}

					map.addPolyline(rectLine);
				}
			//}
		}
	}
	
	@Override
	public void onBackPressed() {
		finish();
		super.onBackPressed();
	}
} 